package com.example.login.controller;

import com.example.login.model.User;
import com.example.login.model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取用户输入的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 创建 User 对象并设置属性
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        // 调用 UserDao 的验证方法
        UserDao userDao = new UserDao();
        boolean isAuthenticated = false;
        try {
            isAuthenticated = userDao.validateUser(user);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        if (isAuthenticated) {
            // 登录成功，跳转到成功页面
            request.getRequestDispatcher("view/success.jsp").forward(request, response);
        } else {
            // 登录失败，设置错误信息并跳转到错误页面
            request.setAttribute("errorMessage", "用户名或密码错误");
            request.getRequestDispatcher("view/error.jsp").forward(request, response);
        }
    }
}